<script lang="ts" setup>
import { ref } from 'vue';

defineOptions({
  name: "ReTable"
});

defineProps({
  // 列配置
  columns: {
    type: Array as () => any[],
    default: () => []
  },
  // 数据
  data: {
    type: Array,
    default: () => []
  },
  // 分页数据
  pagination: {
    type: Object,
    default: () => ({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })
  },
  showSelection: {
    type: Boolean,
    default: false
  },
  showIndex: {
    type: Boolean,
    default: false
  },
  // 选中得行
  selections: {
    type: Array,
    default: () => []
  },
  height: {
    type: Number || String,
    default: () => {
      return 'auto';
    }
  }
});

const emits = defineEmits(["sizeChange", "currentChange", 'selectionChange']);

// 分页条数发生变化
const handleSizeChange = (val: number) => {
  emits("sizeChange", val);
};

// 页码发生变化
const handleCurrentChange = (val: number) => {
  emits("currentChange", val);
};

// 选中行发生变化
const handleSelectionChange = (val: any[]) => {
  emits("selectionChange", val);
};

// 表格ref
const tableRef = ref(null);
defineExpose({
  tableRef
})

</script>

<template>
  <div class="table-container">
    <div class="table-content">
      <ElTable width="100%" :height="height" stripe border :data="data" ref="tableRef" :row-key="row => row.id"
        @selection-change="handleSelectionChange">
        <ElTableColumn v-if="showIndex" type="index" label="序号" width="80" align="center" />
        <el-table-column v-if="showSelection" :reserve-selection="true" type="selection" width="55" />
        <ElTableColumn v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label"
          :align="item.align || 'center'" v-bind="{ ...item.config }">
          <template #default="scope" v-if="item.slotName">
            <slot :name="item.slotName" :row="scope.row"></slot>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <div class="pagination" v-if="pagination.total > 0">
      <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<style scoped>
.table-container {
  display: flex;
  flex-flow: column;
  height: inherit;

  :deep(.el-table th.el-table__cell) {
    background-color: #ebf5ff !important;
  }
}

.table-content {
  flex: 1;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
